#include "Epoll_Network/include/heartbeatmanager.h"

HeartBeatManager HeartBeatManager::instance;

HeartBeatManager *HeartBeatManager::getInstance()
{
    return &instance;
}

void HeartBeatManager::addSocket(int socket)
{
    auto start=std::chrono::high_resolution_clock::now();
    mtx.lock();
    socket_list.push_back({socket,start});
    mtx.unlock();
}

void HeartBeatManager::removeSocket(int socket)
{
    mtx.lock();
    socket_list.erase(std::remove_if(socket_list.begin(),socket_list.end(),
                                     [&socket](const SocketBlock& item){
                                return item.socket==socket;
                        }),socket_list.end());
    mtx.unlock();
}


void HeartBeatManager::workFunc(const HeartBeatManager *obj)
{
    std::list<SqlConnSet*>::iterator it;
    while(1)
    {
        for(SocketBlock cur_block:socket_list)
        {
            auto cur_time=std::chrono::high_resolution_clock::now();
            auto last_time=cur_block.start_time;
            auto during_time=std::chrono::duration_cast<std::chrono::milliseconds>(cur_time-last_time);
            int free_time_int=static_cast<int>(during_time.count());
            if(free_time_int>=2000)
            {
                std::string heartbeat;
                JsonEncoder::getInstance().HeartBeatMsg(heartbeat);
                TcpServer::sendMsg(cur_block.socket,heartbeat);
            }
            else if(free_time_int>=8000)
            {

            }
            else{
                continue;
            }
        }
    }
}
